﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.UI.Filters;
using System.Web.Security;
using CNKI.TPI.Web.UI.Models;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using CNKI.TPI.Web.Search.BLL;
using System.Web.SessionState;
using CNKI.TPI.Web.Admin.IBLL;

namespace CNKI.TPI.Web.UI.Controllers.Search
{
    [SessionState(SessionStateBehavior.ReadOnly)]
    public class HomeController : BaseController
    {
        private IUserService userService = null;
        private ISearchService searchService = null;
        private IHomeService homeService = null;
        private INaviService naviService = null;
        private ISingleDBPublishService singleService = null;

        public HomeController(IUserService userService, ISearchService searchService, IHomeService homeService, INaviService naviService, ISingleDBPublishService singleService)
        {
            this.userService = generator.CreateInterfaceProxyWithTarget<IUserService>(userService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.homeService = generator.CreateInterfaceProxyWithTarget<IHomeService>(homeService, new IInterceptor[] { new LogInterceptor() });
            this.naviService = generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });
            this.singleService = generator.CreateInterfaceProxyWithTarget<ISingleDBPublishService>(singleService, new IInterceptor[] { new LogInterceptor() });
        }

        public ActionResult Index()
        {
            //相似词搜索网址
            //ViewBag.smartWordAddress = ConfigHelper.GetAppSettingsValue("smartWordAddress");

            if (Request.Cookies["SelectedDBInfo"] != null)
            {
                Response.Cookies.Remove("SelectedDBInfo");
            }
            //DRSManager.UpdateDRSInfo();
            ViewBag.SeachInfo = searchService.GetUnionFieldList(FieldType.Search);
            ViewBag.SeachDataBase = searchService.GetUnionDBList();
            //获取跨库分类
            ViewBag.UnionDBClassInfo = searchService.GetUnionClass();


            //左侧
            ViewBag.NumLeft = 0;
            IList<SYS_CMS_NEWS_NEWSCONTENTCONFIG> strListH = homeService.GetHomepageConfig(ShowLocation.Left, PermissionOption.None);
            if (strListH != null && strListH.Count > 0)
            {
                ViewBag.LeftResult = strListH;
                ViewBag.NumLeft = strListH.Count;
            }

            //右侧
            ViewBag.NumRight = 0;
            IList<SYS_CMS_NEWS_NEWSCONTENTCONFIG> strListNotice = homeService.GetHomepageConfig(ShowLocation.Right, PermissionOption.None);
            if (strListNotice != null && strListNotice.Count > 0)
            {
                ViewBag.RightResult = strListNotice;
                ViewBag.NumRight = strListNotice.Count;
            }


            //友情链接 左侧
            IList<SYS_CMS_NEWS_JUMPTEMPLATE> strListLink = homeService.GetHomepageJumpConfig(ShowLocation.Left, PermissionOption.None);
            if (strListLink != null && strListLink.Count > 0)
            {

                ViewBag.HomeLink = strListLink;
                ViewBag.LinkCount = strListLink.Count;
            }
            //友情链接 右侧
            IList<SYS_CMS_NEWS_JUMPTEMPLATE> strListLinkright = homeService.GetHomepageJumpConfig(ShowLocation.Right, PermissionOption.None);
            if (strListLinkright != null && strListLinkright.Count > 0)
            {

                ViewBag.HomeLinkRight = strListLinkright;
                ViewBag.LinkCountRight = strListLinkright.Count;
            }


            return View();
        }

        public ActionResult Login(string returnUrl)
        {
            if (null != returnUrl)
            {
                ViewBag.ReturnUrl = returnUrl;
            }
            else
            {
                //ViewBag.ReturnUrl = Request.UrlReferrer.AbsolutePath;
            }
            return View();
        }

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //[ValidateInput(false)]
        //public ActionResult Login(LoginModel model, string returnUrl)
        //{
        //    LoginUserInfo user = userService.ValidateUser(model.UserName, model.Password);
        //    if (null != user)
        //    {
        //        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
        //            1,
        //            string.IsNullOrEmpty(user.UserName) ? user.UserCode : user.UserName,
        //            DateTime.Now,
        //            DateTime.Now.AddMinutes(30),
        //            false,
        //            user.UserCode + ":" + string.Join(",", user.Role.Select(p => p.Name))
        //            );
        //        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
        //        System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        //        System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
        //        Session.Add("UserInfo", user);
        //        return RedirectToLocal(returnUrl);
        //    }
        //    //if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        //    //{
        //    //    return RedirectToLocal(returnUrl);
        //    //}

        //    // 如果我们进行到这一步时某个地方出错，则重新显示表单
        //    ModelState.AddModelError("", "提供的用户名或密码不正确。");
        //    return View(model);
        //}

        //private ActionResult RedirectToLocal(string returnUrl)
        //{
        //    if (Url.IsLocalUrl(returnUrl))
        //    {
        //        return Redirect(returnUrl);
        //    }
        //    else
        //    {
        //        return RedirectToAction("Index", "Home");
        //    }
        //}

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult LogOff()
        //{
        //    FormsAuthentication.SignOut();
        //    //Session.Remove("UserInfo");
        //    //WebSecurity.Logout();
        //    return RedirectToAction("Index", "Home");
        //}

        public ActionResult DocResource()
        {
            //DataTable userList = userService.GetAllUser();
            return View();
        }

        public ActionResult MediaResource()
        {
            //DataTable userList = userService.GetAllUser();
            return View();
        }

        public ActionResult Introduce()
        {
            //DataTable userList = userService.GetAllUser();
            return View();
        }

        public ActionResult Caseshow()
        {
            //DataTable userList = userService.GetAllUser();
            return View();
        }

        public ActionResult Download()
        {
            //DataTable userList = userService.GetAllUser();
            return View();
        }

        public ActionResult Help()
        {
            //DataTable userList = userService.GetAllUser();
            return View();
        }

        //[CustAuth(Test="user")]
        public ActionResult About()
        {
            ViewBag.Message = "你的应用程序说明页。";

            return View();
        }

        //[CustAuth(Roles="admin")]
        public ActionResult Contact()
        {
            ViewBag.Message = "你的联系方式页。";

            return View();
        }

        /// <summary>
        /// 存菜单标识url
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public void SetMenuSession()
        {
            string url = "/";
            url = Request.QueryString["url"];
            HttpCookie cookie = new HttpCookie("MenuSession");
            cookie.Value = url;
            Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 获取菜单标识url
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public string GetMenuSession()
        {
            string url = "/";
            if (Request.Cookies["MenuSession"] != null)
            {
                string value = Request.Cookies["MenuSession"].Value;
                url = value == null ? "/" : value;
            }
            return url;
        }

        [OutputCache(CacheProfile = "HtmlCache")]
        public ActionResult SubIndexHome()
        {
            string orderstr = "";
            int dbId = int.Parse(Request.Params["dbId"].ToString());
            int type = int.Parse(Request.Params["type"].ToString());
            int len = int.Parse(Request.Params["len"].ToString());
            int pageSize = int.Parse(Request.Params["pageSize"].ToString());
            int location = int.Parse(Request.Params["location"].ToString());//左侧右侧
            SYS_CMS_DATABASE obj = searchService.GetDataByID(dbId);
            if (type != (int)ShowType.JumpTemplate)
            {
                string str = ColumnAliasHelper.GetColumn(obj.DatabaseCode, "SYS_FLD_SYSID");
                if (str != "")
                {
                    orderstr = str + " desc";
                }
            }
            string videoLibID = ConfigHelper.GetAppSettingsValue("VideoLibID");
            string picLibID = ConfigHelper.GetAppSettingsValue("PicLibID");
            string audioLibID = ConfigHelper.GetAppSettingsValue("AudioLibID");
            string eBookLibID = ConfigHelper.GetAppSettingsValue("EBookLibID");
            if (obj != null)
            {
                IList<SearchQuery> searchQuery = new List<SearchQuery>();
                if (obj.RecordCheckPubFlag == 1 && obj.SearchType == (int)SearchType.TPI) //审核标识
                {
                    searchQuery.Add(new SearchQuery("SYS_FLD_CHECKSTATE", "2", ConditionType.Eq, SearchMatchType.And));//过滤审核通过的
                }
                DataSet dsDoc = searchService.SingleSearch(dbId, obj.DatabaseCode, searchQuery, 0, "", "", orderstr, 1, pageSize, option: PermissionOption.None);
                if (dsDoc != null && dsDoc.Tables.Count > 0 && dsDoc.Tables[0].Rows.Count > 0)
                {
                    ViewBag.Type = type;

                    if (videoLibID.Equals(obj.TemplateID.ToString()))
                    {
                        ViewBag.DbType = (int)MediaType.Video;
                    }
                    else if (picLibID.Equals(obj.TemplateID.ToString()))
                    {
                        ViewBag.DbType = (int)MediaType.Pic;
                    }
                    else if (audioLibID.Equals(obj.TemplateID.ToString()))
                    {
                        ViewBag.DbType = (int)MediaType.Audio;
                    }
                    else if (eBookLibID.Equals(obj.TemplateID.ToString()))
                    {
                        ViewBag.DbType = (int)MediaType.Ebook;
                    }
                    else
                    {
                        ViewBag.DbType = 0;
                    }


                    ViewBag.Len = len;
                    ViewBag.ActiclNum = pageSize;
                    ViewBag.SearchResultDoc = dsDoc.Tables[0];
                    ViewBag.DbID = dbId;
                    ViewBag.DbName = obj.DatabaseCode;
                    ViewBag.DisplayDBName = obj.DatabaseName;
                    ViewBag.Location = location;
                    if (type == (int)ShowType.ArticleNews || type == (int)ShowType.PicNews)
                    {
                        //获取对应的文件信息
                        ViewBag.FileInfoHome = searchService.GetFile(int.Parse(dsDoc.Tables[0].Rows[0]["SYS_FLD_SYSID"].ToString()), obj.DatabaseCode, MediaType.Pic);
                    }
                }
            }

            return PartialView("SubIndex");
        }

        [OutputCache(CacheProfile = "HtmlCache")]
        public ActionResult HomeDataBase()
        {
            int len = 12;
            ViewBag.Type = -1;//数据库列表标志
            ////数据库列表文献
            //ViewBag.DatabaseList = naviService.GetDataBaseList(PermissionOption.None);
            //数据库列表多媒体
            //ViewBag.MediaResource = naviService.GetMediaResourceList();
            ViewBag.DatabaseList = singleService.GetDBList(null).Where(c => c.VisibleFlag == 1 && c.DatabasePubFlag == 1).ToList();
            if (ConfigHelper.GetAppSettingsValue("ShowDbList") != "")
            {
                len = int.Parse(ConfigHelper.GetAppSettingsValue("ShowDbList"));
            }
            ViewBag.ShowDbList = len;//首页数据库列表显示条数s
            return PartialView("SubIndex");

        }

        [OutputCache(CacheProfile = "HtmlCache")]
        public ActionResult HomeDataBaseXC()
        {
            int len = 12;
            ViewBag.Type = -1;//数据库列表标志
            ////数据库列表文献
            //ViewBag.DatabaseList = naviService.GetDataBaseList(PermissionOption.None);
            //数据库列表多媒体
            //ViewBag.MediaResource = naviService.GetMediaResourceList();
            ViewBag.DatabaseList = singleService.GetDBList(null).Where(c => c.VisibleFlag == 1 && c.DatabasePubFlag == 1).ToList();
            if (ConfigHelper.GetAppSettingsValue("ShowDbList") != "")
            {
                len = int.Parse(ConfigHelper.GetAppSettingsValue("ShowDbList"));
            }
            ViewBag.ShowDbList = len;//首页数据库列表显示条数s
            return PartialView("SubIndexXC");

        }
        
    }
}
